#nullable disable
using ERPBackend.Data;
using ERPBackend.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using System;

namespace ERPBackend.Services
{
    public class PurchaseOrderService : IPurchaseOrderService
    {
        private readonly ApplicationDbContext _context;

        public PurchaseOrderService(ApplicationDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }

        public async Task<IEnumerable<PurchaseOrder>> GetAllPurchaseOrdersAsync()
        {
            return await _context.PurchaseOrders
                .Include(po => po.Supplier)
                .Include(po => po.PurchaseOrderItems)
                    .ThenInclude(poi => poi.Material)
                .ToListAsync();
        }

        public async Task<PurchaseOrder?> GetPurchaseOrderByIdAsync(int id)
        {
            return await _context.PurchaseOrders
                .Include(po => po.Supplier)
                .Include(po => po.PurchaseOrderItems)
                    .ThenInclude(poi => poi.Material)
                .FirstOrDefaultAsync(po => po.Id == id);
        }

        public async Task<IEnumerable<PurchaseOrder>> GetPurchaseOrdersBySupplierIdAsync(int supplierId)
        {
            return await _context.PurchaseOrders
                .Include(po => po.Supplier)
                .Include(po => po.PurchaseOrderItems)
                    .ThenInclude(poi => poi.Material)
                .Where(po => po.SupplierId == supplierId)
                .ToListAsync();
        }

        public async Task<IEnumerable<PurchaseOrder>> SearchPurchaseOrdersAsync(string orderCode, int? status, DateOnly? startDate, DateOnly? endDate)
        {
            var query = _context.PurchaseOrders
                .Include(po => po.Supplier)
                .Include(po => po.PurchaseOrderItems)
                    .ThenInclude(poi => poi.Material)
                .AsQueryable();

            if (!string.IsNullOrEmpty(orderCode))
            {
                query = query.Where(po => po.OrderCode.Contains(orderCode));
            }

            if (status.HasValue)
            {
                query = query.Where(po => po.Status == status.Value);
            }

            if (startDate.HasValue)
            {
                query = query.Where(po => po.OrderDate >= startDate.Value);
            }

            if (endDate.HasValue)
            {
                query = query.Where(po => po.OrderDate <= endDate.Value);
            }

            return await query.ToListAsync();
        }

        public async Task<PurchaseOrder> CreatePurchaseOrderAsync(PurchaseOrder purchaseOrder)
        {
            // 验证供应商是否存在
            var supplierExists = await _context.Suppliers.AnyAsync(s => s.Id == purchaseOrder.SupplierId);
            if (!supplierExists)
            {
                throw new ArgumentException("Invalid supplier id");
            }

            // 验证订单明细
            if (purchaseOrder.PurchaseOrderItems == null || !purchaseOrder.PurchaseOrderItems.Any())
            {
                throw new ArgumentException("Purchase order must have at least one item");
            }

            // 验证物料是否存在并计算金额
            decimal totalAmount = 0;
            foreach (var item in purchaseOrder.PurchaseOrderItems)
            {
                var materialExists = await _context.Materials.AnyAsync(m => m.Id == item.MaterialId);
                if (!materialExists)
                {
                    throw new ArgumentException($"Invalid material id: {item.MaterialId}");
                }

                // 计算金额
                item.Amount = item.Quantity * item.UnitPrice;
                item.TaxAmount = item.Amount * item.TaxRate;
                item.TotalAmount = item.Amount + item.TaxAmount;
                totalAmount += item.TotalAmount;
            }

            // 设置订单总金额
            purchaseOrder.TotalAmount = totalAmount;
            purchaseOrder.UnpaidAmount = totalAmount;
            purchaseOrder.PaidAmount = 0;
            purchaseOrder.Status = 0; // 待审核
            purchaseOrder.CreatedAt = DateTime.Now;

            // 添加到数据库
            _context.PurchaseOrders.Add(purchaseOrder);
            await _context.SaveChangesAsync();
            return purchaseOrder;
        }

        public async Task<bool> UpdatePurchaseOrderAsync(PurchaseOrder purchaseOrder)
        {
            // 检查订单是否存在
            var existingOrder = await _context.PurchaseOrders.FindAsync(purchaseOrder.Id);
            if (existingOrder == null)
            {
                return false;
            }

            // 已审核的订单只能修改部分字段
            if (existingOrder.Status > 0)
            {
                throw new ArgumentException("Cannot modify an approved purchase order");
            }

            // 验证供应商是否存在
            var supplierExists = await _context.Suppliers.AnyAsync(s => s.Id == purchaseOrder.SupplierId);
            if (!supplierExists)
            {
                return false;
            }

            // 验证订单明细
            if (purchaseOrder.PurchaseOrderItems == null || !purchaseOrder.PurchaseOrderItems.Any())
            {
                return false;
            }

            // 删除旧的订单明细
            var oldItems = await _context.PurchaseOrderItems.Where(poi => poi.PurchaseOrderId == purchaseOrder.Id).ToListAsync();
            _context.PurchaseOrderItems.RemoveRange(oldItems);

            // 验证新的物料并计算金额
            decimal totalAmount = 0;
            foreach (var item in purchaseOrder.PurchaseOrderItems)
            {
                var materialExists = await _context.Materials.AnyAsync(m => m.Id == item.MaterialId);
                if (!materialExists)
                {
                    throw new ArgumentException($"Invalid material id: {item.MaterialId}");
                }

                // 计算金额
                item.Amount = item.Quantity * item.UnitPrice;
                item.TaxAmount = item.Amount * item.TaxRate;
                item.TotalAmount = item.Amount + item.TaxAmount;
                totalAmount += item.TotalAmount;
                item.PurchaseOrderId = purchaseOrder.Id;
            }

            // 更新订单信息
            existingOrder.SupplierId = purchaseOrder.SupplierId;
            existingOrder.OrderDate = purchaseOrder.OrderDate;
            existingOrder.ExpectedDeliveryDate = purchaseOrder.ExpectedDeliveryDate;
            existingOrder.PaymentTerms = purchaseOrder.PaymentTerms;
            existingOrder.DeliveryMethod = purchaseOrder.DeliveryMethod;
            existingOrder.FreightResponsibility = purchaseOrder.FreightResponsibility;
            existingOrder.TotalAmount = totalAmount;
            existingOrder.UnpaidAmount = totalAmount - existingOrder.PaidAmount;
            existingOrder.UpdatedAt = DateTime.Now;
            existingOrder.UpdatedBy = purchaseOrder.UpdatedBy;

            // 添加新的订单明细
            _context.PurchaseOrderItems.AddRange(purchaseOrder.PurchaseOrderItems);

            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> DeletePurchaseOrderAsync(int id)
        {
            var purchaseOrder = await _context.PurchaseOrders.FindAsync(id);
            if (purchaseOrder == null)
            {
                return false;
            }

            // 已审核的订单不能删除
            if (purchaseOrder.Status > 0)
            {
                throw new ArgumentException("Cannot delete an approved purchase order");
            }

            // 删除订单明细
            var orderItems = await _context.PurchaseOrderItems.Where(poi => poi.PurchaseOrderId == id).ToListAsync();
            _context.PurchaseOrderItems.RemoveRange(orderItems);

            // 删除订单
            _context.PurchaseOrders.Remove(purchaseOrder);
            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> ReviewPurchaseOrderAsync(int id, int reviewedBy, bool isApproved, string comments)
        {
            var purchaseOrder = await _context.PurchaseOrders.FindAsync(id);
            if (purchaseOrder == null)
            {
                return false;
            }

            // 只能审核待审核的订单
            if (purchaseOrder.Status != 0)
            {
                throw new ArgumentException("Only pending purchase orders can be reviewed");
            }

            // 更新订单状态
            purchaseOrder.Status = isApproved ? (byte)1 : (byte)4; // 1: 已审核, 4: 已取消
            purchaseOrder.ReviewedBy = reviewedBy;
            purchaseOrder.ReviewedAt = DateTime.Now;

            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> ClosePurchaseOrderAsync(int id, int closedBy, string reason)
        {
            var purchaseOrder = await _context.PurchaseOrders.FindAsync(id);
            if (purchaseOrder == null)
            {
                return false;
            }

            // 只能关闭已完成的订单
            if (purchaseOrder.Status != 2)
            {
                throw new ArgumentException("Only completed purchase orders can be closed");
            }

            // 更新订单状态
            purchaseOrder.Status = 3; // 已关闭
            purchaseOrder.ClosedBy = closedBy;
            purchaseOrder.ClosedAt = DateTime.Now;
            purchaseOrder.CloseReason = reason;

            await _context.SaveChangesAsync();
            return true;
        }
    }
}